//
//  MovieViewController.m
//  One
//
//  Created by mac on 16-5-19.
//  Copyright (c) 2016年 mac. All rights reserved.
//

#import "MovieViewController.h"
#import "MovieTableViewCell.h"
#import "MovieObject.h"
#import "MovieDetailVC.h"

@interface MovieViewController ()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *listArray;
    MJRefreshBackNormalFooter *footer;
    NSArray *nowArr;
    NSTimer *timer;
    //int totalCount;
    NSMutableArray *totalTimeArray;
}
@end

@implementation MovieViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    timer = nil;
    
    [self.myTable registerNib:[UINib nibWithNibName:@"MovieTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cell"];
    
    footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        [self getMoreListData];
    }];
    [footer setTitle:@"没有更多数据" forState:MJRefreshStateNoMoreData];
    _myTable.mj_footer = footer;
    
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self getMovieListData];
}

#pragma mark--TableViewDelegate

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return (HEIGHT- 40)/4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return listArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    MovieTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    MovieListObject *obj = listArray[indexPath.row];
    cell.movieBgImgView.image = [UIImage imageNamed:[NSString stringWithFormat:@"movie_image_%ld.jpg_unsliced",indexPath.row%12+1]];
    if (obj.score == nil) {
        cell.LineImgView.image = nil;
        cell.movieScoreLabel.text = nil;
        
        BOOL isFire = [self judgeDateWithDateObj:obj cellIndexRow:(int)indexPath.row ];
        
        if (isFire) {
        }else
        {
        cell.showTimeLabel.text = @"即将上映";
        }
        
    }else
    {
        cell.movieScoreLabel.text = obj.score;
        cell.LineImgView.image = [UIImage imageNamed:@"redline_81x5_"];
        cell.showTimeLabel.text = nil;
    }
    if (obj != nil) {
     
        [cell.movieBgImgView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@",obj.cover]]];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MovieListObject *obj = listArray[indexPath.row];
    MovieDetailVC *DetailVC = [[MovieDetailVC alloc ] init];
    DetailVC.topicObj = obj;
    DetailVC.title = [NSString stringWithFormat:@"%@",obj.title];
    DetailVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:DetailVC animated:YES];
}

#pragma mark--获取数据
- (void)getMovieListData
{
    NSDictionary *parameter = @{URLKEY : @"movie/list/0"};
    [HttpManager requestDataWithParameters:parameter requestMethod:@"GET" completionBlock:^(NSDictionary *responseDic) {
        NSArray *arr = responseDic[@"data"];
        listArray = [[NSMutableArray alloc] init];
        [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            MovieListObject *listObj = [MovieListObject mj_objectWithKeyValues:obj];
            [listArray addObject:listObj];
            [_myTable reloadData];
        }];
    }];
}

- (void)getMoreListData
{

    MovieListObject *obj = [listArray lastObject];

    NSDictionary *para = @{URLKEY : [NSString stringWithFormat:@"movie/list/%@",obj.ID]};
    [HttpManager requestDataWithParameters:para requestMethod:@"GET" completionBlock:^(NSDictionary *responseDic) {
        NSArray *arr = responseDic[@"data"];
        if (arr.count == 0) {
            [self.myTable.mj_footer endRefreshingWithNoMoreData];
        }else
        {
        [arr enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
            
            
            MovieListObject *listObj = [MovieListObject mj_objectWithKeyValues:obj ];
            [listArray addObject:listObj];
            [self.myTable reloadData];
        }];
            [self.myTable.mj_footer endRefreshing];
        }
    }];

}

#pragma mark--倒计时

- (BOOL)judgeDateWithDateObj:(MovieListObject *)obj cellIndexRow:(int)row
{
    [self getCurrentDate];
    NSArray *timeArr = [obj.releasetime componentsSeparatedByString:@" "];
    
    if ([nowArr[0] isEqualToString:[NSString stringWithFormat:@"%@",timeArr[0]]]) {
        
        NSString *timeStr = [nowArr lastObject];
        NSArray *TimeNumArr = [timeStr componentsSeparatedByString:@":"];
        int hc = 23 - [TimeNumArr[0] intValue];
        int mc = 60 - [TimeNumArr[1] intValue];
        int sc = 60 - [TimeNumArr[2] intValue];
        int totalCount = hc * 60 * 60 + mc* 60 + sc;
        totalTimeArray = [[NSMutableArray alloc] init];
        NSDictionary *dic = @{
                              @"indexPath":[NSString stringWithFormat:@"%d",row],
                              @"totalTime":[NSNumber numberWithInt:totalCount]
                              };
        [totalTimeArray addObject:dic];
            [self fireTheNStimer];
        return YES;
    }else
    {
        return NO;
    }
}

- (void)getCurrentDate
{
    NSDateFormatter *formate = [[NSDateFormatter alloc ] init];
    [formate setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *now = [NSDate  date];
    NSString *nowTime = [formate stringFromDate:now];
    nowArr = [nowTime componentsSeparatedByString:@" "];
}

- (void)fireTheNStimer
{
    if (timer == nil) {
        timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(onTimer) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:UITrackingRunLoopMode];
         [timer fire];
    }else
    {
    
        return;
    }
}

- (void)onTimer
{
    int time;
    for (int i = 0; i <totalTimeArray.count; i ++) {
        time = [[[totalTimeArray objectAtIndex:i] objectForKey:@"totalTime"] intValue];
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:[[[totalTimeArray objectAtIndex:i] objectForKey:@"indexPath"] intValue] inSection:0];
        NSDictionary *dic = @{
                              @"indexPath":[NSString stringWithFormat:@"%ld",(long)indexPath.row],
                              @"totalTime":[NSString stringWithFormat:@"%d",--time]
                              };
        [totalTimeArray replaceObjectAtIndex:i withObject:dic];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            MovieTableViewCell *cell = (MovieTableViewCell *)[self.myTable cellForRowAtIndexPath:indexPath];
            NSString *timeStr = [self lessSecondWithSecond:time];
            cell.showTimeLabel.text = [NSString stringWithFormat:@"距离公开分数还有： %@",timeStr];
        });
    }
    
}


- (NSString *)lessSecondWithSecond:(int)totalTime
{
    int hour =  totalTime/3600;
    int min = (totalTime%3600)/60;
    int sec = totalTime%60;
    
    NSString *str1 = [self judgeWithTime:hour];
    NSString *str2 = [self judgeWithTime:min];
    NSString *str3 = [self judgeWithTime:sec];
    NSString *time = [NSString stringWithFormat:@"%@:%@:%@",str1,str2,str3];
    return time;
}

- (NSString *)judgeWithTime:(int)num
{
    NSString *str;
    if (num < 10) {
        str = [NSString stringWithFormat:@"0%d",num];
    }else
    {
        str = [NSString stringWithFormat:@"%d",num];
    }
    return str;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
